package com.cms.controller;


import com.cms.dto.LoginDTO;
import com.cms.entity.User;
import com.cms.service.UserService;
import com.cms.vo.Result;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/login")
@Slf4j
public class LoginController {

    @Resource
    private UserService userService;

    // 登录处理
    @PostMapping("/handler")
    @ResponseBody
    public String login(LoginDTO loginDTO, Model model){
        Gson gson = new Gson();

        if (loginDTO.getCode().equals("1234") && loginDTO.getCode() != null) {
            try {
                User user = userService.login(loginDTO);
                if (user == null) {
                    return gson.toJson(Result.error(502, "Username Or Password Error"));
                } else {
                    model.addAttribute("user", user);
                    return gson.toJson(Result.success("index"));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return gson.toJson(Result.error(501, "Code Error"));
        }
    }

    // 登录页面
    @GetMapping("/")
    public String login(){
        return "login";
    }

    // 主页
    @GetMapping("/index")
    public String index(){
        return "index";
    }

}
